package com.zhl.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhl.entity.ZhlResult;
import com.zhl.utils.MinioUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/19.
 */
@Controller
@RequestMapping("/api")
public class SourceCotroller {

    @Value("${miniourl}")
    private String miniourl;
    @Value("${AccessKey}")
    private String AccessKey;
    @Value("${SecretKey}")
    private String SecretKey;

    private static Logger logger = LoggerFactory.getLogger("SourceCotroller");

    /**
     * 图片上传
     *
     * @param request
     * @param files
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    @RequestMapping(value = "/upload/file")
    @ResponseBody
    public ZhlResult uploadfile(HttpServletRequest request, @RequestParam List<MultipartFile> files) throws IOException {

        String imageCosUrl = "";
        try {

            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multiRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){

                JSONObject jsonObject = upload(entry);

                if (jsonObject != null && jsonObject.getString("flag").equals("-1")) {
                    logger.info("====上传图片出错");
                    return ZhlResult.fail("保存文件出错");
                } else {
                    imageCosUrl = jsonObject.getString("url");
                }
            }
            logger.info("上传成功 = " + imageCosUrl);
            return ZhlResult.ok(imageCosUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return ZhlResult.fail("保存文件出错");
        }
    }

    /**
     * 图片上传
     *
     * @param request
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    @RequestMapping(value = "/file")
    @ResponseBody
    public String uploadfile(HttpServletRequest request) throws IOException {

        String imageCosUrl = "";
        try {

            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multiRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){

                JSONObject jsonObject = upload(entry);

                if (jsonObject != null && jsonObject.getString("flag").equals("-1")) {
                    logger.info("====上传图片出错");
                    return "保存文件出错";
                } else {
                    imageCosUrl = jsonObject.getString("url");
                }
            }

            logger.info("上传成功 = " + imageCosUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageCosUrl;

    }

    //上传方法
    private JSONObject upload(Map.Entry<String, MultipartFile> entry) throws Exception {
        MultipartFile file = entry.getValue();

        BufferedImage bi = ImageIO.read(file.getInputStream());

        logger.info("上传图片的宽：" + bi.getWidth() + "，图片的高:" + bi.getHeight());

        String[] uploadSuffixs = file.getOriginalFilename().split("\\.");

        String suffix = "." + uploadSuffixs[(uploadSuffixs.length - 1)];
        JSONObject jsonObject = MinioUtil.uploadImage(file.getInputStream(), suffix, AccessKey, SecretKey);
        logger.info("====上传结果:" + jsonObject.toJSONString());
        return jsonObject;
    }


    //增加修改页删除图片，保留
    @ResponseBody
    @RequestMapping(value = "/removeimg", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public ZhlResult removeImg(HttpServletRequest request, @RequestBody JSONObject requestParams) throws Exception {
        String paths = requestParams.get("id").toString();
        String tempPath = "", result = "更新成功";
        String[] pathlist = paths.split(",");

        for (int i = 0; i < pathlist.length; i++) {
            //切割掉前面的内容:http://www.itzhl.club:9000/lingziyang
            tempPath = pathlist[i].substring(miniourl.length());
            logger.info("tempPath:" + tempPath);
            MinioUtil.imageDelete(tempPath,AccessKey, SecretKey);
        }

        return ZhlResult.ok();
    }


}
